import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import './TaskSystem.css';

const TaskSystem = forwardRef(({ petState, gameInfo, onCompleteTask }, ref) => {
  // 任务列表
  const [tasks, setTasks] = useState([
    {
      id: 1,
      title: '喂食3次',
      description: '给宠物喂食3次',
      reward: 30,
      progress: 0,
      target: 3,
      type: 'feed',
      completed: false
    },
    {
      id: 2,
      title: '玩耍5次',
      description: '和宠物玩耍5次',
      reward: 50,
      progress: 0,
      target: 5,
      type: 'play',
      completed: false
    },
    {
      id: 3,
      title: '保持健康',
      description: '保持宠物健康度在80以上3天',
      reward: 100,
      progress: 0,
      target: 3,
      type: 'health',
      completed: false
    }
  ]);

  // 更新任务进度
  useEffect(() => {
    const updateTasks = () => {
      setTasks(prevTasks => {
        return prevTasks.map(task => {
          // 如果任务已完成，不再更新
          if (task.completed) return task;
          
          let newProgress = task.progress;
          
          // 根据任务类型更新进度
          switch(task.type) {
            case 'health':
              if (petState.health >= 80) {
                newProgress = Math.min(task.progress + 1, task.target);
              }
              break;
            default:
              break;
          }
          
          // 检查任务是否完成
          const isCompleted = newProgress >= task.target;
          
          // 如果任务刚刚完成，触发完成回调
          if (isCompleted && !task.completed) {
            onCompleteTask(task.reward);
          }
          
          return {
            ...task,
            progress: newProgress,
            completed: isCompleted
          };
        });
      });
    };
    
    // 每天更新一次任务进度
    const taskTimer = setInterval(updateTasks, 10000);
    
    return () => clearInterval(taskTimer);
  }, [petState, onCompleteTask]);

  // 更新喂食和玩耍任务的进度
  const updateActionTask = (actionType) => {
    setTasks(prevTasks => {
      return prevTasks.map(task => {
        if (task.completed || task.type !== actionType) return task;
        
        const newProgress = Math.min(task.progress + 1, task.target);
        const isCompleted = newProgress >= task.target;
        
        if (isCompleted && !task.completed) {
          onCompleteTask(task.reward);
        }
        
        return {
          ...task,
          progress: newProgress,
          completed: isCompleted
        };
      });
    });
  };

  // 暴露更新方法给父组件
  useImperativeHandle(ref, () => ({
    updateFeedTask: () => updateActionTask('feed'),
    updatePlayTask: () => updateActionTask('play'),
  }));

  return (
    <div className="task-system">
      <h3 className="task-title">每日任务</h3>
      <div className="task-list">
        {tasks.map(task => (
          <div key={task.id} className={`task-item ${task.completed ? 'completed' : ''}`}>
            <div className="task-info">
              <h4 className="task-name">{task.title}</h4>
              <p className="task-description">{task.description}</p>
            </div>
            <div className="task-status">
              <div className="task-progress">
                <div 
                  className="task-progress-fill" 
                  style={{ width: `${(task.progress / task.target) * 100}%` }}
                ></div>
              </div>
              <div className="task-numbers">
                <span className="task-progress-text">{task.progress}/{task.target}</span>
                <span className="task-reward">+{task.reward} 💰</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
});

export default TaskSystem;